/**
 * DragNode.cpp
 * Coyright (c) 2009 Xiaofeng Gu. All Rights Reserved.
 * Author : Xiaofeng Gu
 *
 * Creation Data : 2009/09/07
 */

#include "stdafx.h"
#include "DragNode.h"
#include "Global.h"
#include "MathUtil.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

HRESULT CDragNode::OnExecute()
{
	HRESULT hr = S_OK;
	hr = __super::OnExecute();
	if (hr != S_OK)
	{
		return hr;
	}

	bool bOk = false;

	CGViewer* pViewer = CSKGlobal::GetViewer();
	CDragNodeProcessCard* pDragNodeDef = GetBlockInfo<CDragNodeProcessCard>(DRAGNODEDEF_INSTANCE);

	ISelect* pObject = pDragNodeDef->GetSelectObj();
	CTransNode* pNode = dynamic_cast<CTransNode*>(pObject);

	CVec& EyePt = pDragNodeDef->GetEyePt();
	double Ray[6];
	Ray[0] = EyePt[0];
	Ray[1] = EyePt[1];
	Ray[2] = EyePt[2];

	CBone* pBone = pNode->GetBone();
	CJoint Joint = (*pBone)[0];

	double Ball[4];
	Ball[0] = Joint[0];
	Ball[1] = Joint[1];
	Ball[2] = Joint[2];
	Ball[3] = ((*pBone)[1] - (*pBone)[0]).Length();

	int iStartX, iStartY;
	pDragNodeDef->GetStartDragPt(iStartX, iStartY);
	CVec startPt;
	pViewer->ViewToModelSpace(iStartX, iStartY, startPt);
	Ray[3] = startPt[0];
	Ray[4] = startPt[1];
	Ray[5] = startPt[2];
	double BallPt1[3];
	CMathUtil::CalRayToBallPt(Ray, Ball, BallPt1);

	int iStopX, iStopY;
	pDragNodeDef->GetStopDragPt(iStopX, iStopY);
	CVec stopPt;
	pViewer->ViewToModelSpace(iStopX, iStopY, stopPt);
	Ray[3] = stopPt[0];
	Ray[4] = stopPt[1];
	Ray[5] = stopPt[2];
	double BallPt2[3];
	CMathUtil::CalRayToBallPt(Ray, Ball, BallPt2);

	CVec U = CVec(BallPt1[0] - Joint[0], BallPt1[1] - Joint[1], BallPt1[2] - Joint[2]);
	U.Identify();
	CVec V = CVec(BallPt2[0] - Joint[0], BallPt2[1] - Joint[1], BallPt2[2] - Joint[2]);
	V.Identify();
	if (U == V){}
	else
	{
		CVec rot = U ^ V;
		rot.Identify();
		double sita = U.CrossAngle(V);
		pNode->Rotate(rot, sita);
	}

	return S_OK;
}